<?php

namespace App\Models;

use Image;

class Goods extends BaseModel
{
    protected $table = "goods";

    const GOODS_DATA = 'GOODS_DATA';

    protected $rules = [
        'admin_id' => 'required',
        'goods_name' => 'required|between:1,20',
        'goods_price' => ['required', 'numeric', 'regex:/^([1-9]\d*(\.\d*[1-9])?)|(0\.\d*[1-9])/'],
        'shop_price' => 'numeric',
        'goods_num' => 'required|numeric|min:1',
        'category_id' => 'required|numeric',
        'brand_id' => 'required|numeric',
        'bucket_category_id' => 'required|numeric',
    ];

    protected $message = [
        'admin_id.required' => '用户ID获取失败',
        'goods_name.required' => '商品名称必须填写',
        'goods_name.between' => '商品名称不能超过20个字',
        'goods_name.unique' => '该商品名称已存在，请重新输入',
        'goods_price.required' => '商品价格必须填写',
        'goods_price.numeric' => '商品价格必须是纯数字',
        'goods_price.regex' => '商品价格不能小于0',
        'shop_price.numeric' => '市场价格必须是纯数字',
        'goods_num.required' => '商品库存必须填写',
        'goods_num.numeric' => '商品库存必须是纯数字',
        'goods_num.min' => '商品库存不能小于1',
        'category_id.required' => '请选择商品所属分类',
        'category_id.numeric' => '非法分类数据',
        'brand_id.required' => '请选择商品所属品牌',
        'brand_id.numeric' => '非法品牌数据',
        'bucket_category_id.required' => '请选择商品所属水桶分类',
        'bucket_category_id.numeric' => '非法水桶分类数据',
    ];

    public function getGoodsList()
    {
        $keyword = request('keyword');
        if ($keyword) {
            if (is_numeric($keyword)) {
                $where['id'] = $keyword;
            } else {
                $where['goods_name'] = ['like', '%' . $keyword . '%'];
            }
        }
        $rows = $this->_getPageList($where);
        $txtStr['status'] = [1 => '上架', -1 => '下架', 0 => '待上架'];
        $rows['data'] = int_to_string($rows['data'], $txtStr);
        return $rows;
    }

    public function getOwnGoodsList()
    {
        $keyword = request('keyword');
        $where['admin_id'] = plat_admin_id();
//        if (request()->has('shop_id')) {
//            $where['shop_id'] = request('shop_id');
//        }
        if ($keyword) {
            if (is_numeric($keyword)) {
                $where['id'] = $keyword;
            } else {
                $where['goods_name'] = ['like', '%' . $keyword . '%'];
            }
        }
        $rows = $this->_getPageList($where, '*', ['sort' => 'asc']);
        $txtStr['status'] = [1 => '已上架', -1 => '已下架', 0 => '待上架'];
        $rows['data'] = int_to_string($rows['data'], $txtStr);
        return $rows;
    }

    public function getGoodsListByShopId($shopId)
    {
        $keyword = request('keyword');
        $where['shop_id'] = $shopId;
        $where['status'] = ['>', 0];
        if ($keyword) {
            if (is_numeric($keyword)) {
                $where['id'] = $keyword;
            } else {
                $where['goods_name'] = ['like', '%' . $keyword . '%'];
            }
        }
        $rows = $this->_getPageList($where, 'id,goods_name,goods_num,goods_price');
        return $rows;
    }

    public function addOrUpdate($type = 0)
    {
        $data['admin_id'] = plat_admin_id();
        $data['goods_name'] = trim(request('goods_name'));
        $data['goods_price'] = floatval(trim(request('goods_price', 1)));
        $data['shop_price'] = floatval(trim(request('shop_price')));
        $data['goods_num'] = intval(trim(request('goods_num', 1)));
        $data['pic_num'] = count(request('pics'));
        $data['category_id'] = request('category_id');
        $data['bucket_category_id'] = request('bucket_category_id');
        $data['brand_id'] = request('brand_id');
        $data['goods_content'] = request('goods_content', '');
        $data['sort'] = request('sort', 0);
        $data['status'] = request('status', 0);
        if (!$data['category_id']) {
            $this->error = '请选择商品分类！';
            return false;
        }
        if ($data['category_id'] == 1) {
            $this->error = '桶装水商品分类请设置是否回桶！';
            return false;
        }
        if (request('id')) {
            $data['id'] = trim(request('id'));
        } else {
            $data['addtime'] = time();
        }
        if (!$this->_validate($data)) {
            return false;
        }
        //开启事务
        $this->_start();
        $res = $this->_save($data);
        if (!$res) {
            $this->error = '保存商品信息失败！';
            $this->_rollBack(); //回滚
            return false;
        }
        if (!isset($data['id'])) {
            //新增商品同时更新shop表商品总数
            $admin = new Admin();
            $admin->_inc(['id' => $data['admin_id']], 'goods_num');
        }
        $id = isset($data['id']) ? $data['id'] : $res;
        $picture = new Picture();
        $res = $picture->upload($id);
        if (!$res) {
            $this->error = $picture->getError();
            $this->_rollBack(); //回滚
            return false;
        }
        $shopGoods = new ShopGoods();
        if (isset($data['id'])) {
            $where['goods_id'] = $id;
            $sdata['goods_name'] = $data['goods_name'];
            $sdata['goods_price'] = $data['goods_price'];
            $sdata['shop_price'] = $data['shop_price'];
            $sdata['category_id'] = $data['category_id'];
            $sdata['brand_id'] = $data['brand_id'];
            $sdata['bucket_category_id'] = $data['bucket_category_id'];
            $sdata['pic_num'] = $data['pic_num'];
            $sdata['goods_content'] = $data['goods_content'];
            $shopGoods->_update($where, $sdata);
            $waterBill = new WaterBill();
            $waterBill->_update($where, $sdata);
            $shopGoods->_redisGenerateGoodsListByAid(plat_admin_id());
            $waterBill->_redisGenerateBillListByAid(plat_admin_id());
        }
        if ($type) {
            if (empty($data)) {
                $this->error = '无效商品数据';
                return false;
            }
            $shopId = session('shop_info')['id'];
            $newdata = $data;
            $newdata['shop_id'] = $shopId;
            $newdata['goods_id'] = $id;
            $newdata['addtime'] = time();
            unset($newdata['id']);
            if (!$shopGoods->_validate($newdata)) {
                return false;
            }
            $res = $shopGoods->_save($newdata);
            if (!$res) {
                $this->error = '添加失败，请稍后再试';
                return false;
            }
            $shop = new Shop();
            $shop->_inc(['id' => $shopId], 'total_goods_num');
            $shopGoods->_redisGenerateGoodsListByAid(plat_admin_id());
        }
        //记录行为
//        action_log('update_goods', 'goods', $id);
        //提交事务
        $this->_commit();
        return $res;
    }

    public function del()
    {
        $id = request('id');
        if (!$id) {
            $this->error = '请选择要操作的数据!';
            return false;
        }
        $child = $this->_getList(['pid' => $id])->toArray();
        if (!empty($child)) {
            $this->error = '请先删除该品牌下的子品牌';
            return false;
        }
        $res = $this->_del(['id' => $id]);
        if (!$res) {
            $this->error = '删除品牌失败!';
            return false;
        }
        //记录行为
        action_log('update_shop', 'shop', $id);
        return '删除品牌成功';
    }


}
